﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class FrontEnd_Control_Product_List
    Inherits System.Web.UI.UserControl

    Dim level As String = -1
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

#Region "Sub and Function"

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        If Session("UserName") Is Nothing Then
            Dim retURL As String = Request.Path
            Response.Redirect("~/dang-nhap.html?retURL=" & retURL)

        End If
    End Sub
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "abc", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "abc", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            'reset category
            ddlType.Items.Clear()
            getStore()
            getMenu()
            getStatus()
            BindToGrid(1, "")
        End If
    End Sub
    Protected Sub getMenu(Optional ByVal RootCate As Integer = 0)
        Using data As New VSEntities
            Dim query As List(Of Category) = (From q In data.Categories Where q.CatId = 0 Order By q.Sort Ascending Select q).ToList
            ddlType.DataValueField = "CatId"
            ddlType.DataTextField = "Title"

            If Not query Is Nothing Then
                RecursiveFillTree(query, RootCate)
            End If

            Dim itm As New ListItem("--- Tất cả ---", "-1")
            ddlType.Items.Insert(0, itm)
        End Using
    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of Category), ByVal parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1

            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Using data As New VSEntities
            Dim dv As List(Of Category) = (From q In data.Categories Where q.ParentId = parentID Select q).ToList
            Dim i As Integer
            If dv.Count > 0 Then
                For i = 0 To dv.Count - 1
                    Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).CatId.ToString())
                    ddlType.Items.Add(itm)
                    RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).CatId.ToString()))
                Next

            End If
        End Using
        level -= 1
        'on the each function end level will decrement by 1
    End Sub

    Protected Sub getStatus()
        ddlStatus.Items.Clear()
        ddlStatus.AppendDataBoundItems = True
        ddlStatus.Items.Add(New ListItem("--- Tất cả ---", "-1"))
        Using data As New VSEntities
            Dim p = (From q In data.Status Select q.StatusId, q.Title).ToList
            ddlStatus.DataValueField = "StatusId"
            ddlStatus.DataTextField = "Title"
            ddlStatus.DataSource = p
            ddlStatus.DataBind()
            ddlStatus.SelectedValue = -1
        End Using

    End Sub
    Protected Sub getStore()
        Dim curUser As Integer = Session("UserId")
        Using data As New VSEntities
            Dim p = (From q In data.Stores Where q.UserId = curUser Select q).ToList
            Dim k = (From q In data.Stores Where q.UserId = curUser Select q.StoreId).ToList
            Dim listRootCate = (From q In data.StoreTypes Where k.Contains(q.StoreID) Order By q.Category.Sort Select q.RootCateId).ToList
            For Each rootCate In listRootCate
                '   getMenu(rootCate)
            Next
        End Using
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, _
                           Optional ByVal strTitle As String = "", _
                           Optional ByVal intStoreId As Integer = -1, _
                           Optional ByVal dtmCreatedFrom As Date = #1/1/1900#, _
                           Optional ByVal dtmCreatedTo As Date = #12/31/3999#, _
                           Optional ByVal intIsSellOff As Integer = -1, _
                           Optional ByVal intIsHot As Integer = -1, _
                           Optional ByVal intStatusId As Integer = -1, _
                           Optional ByVal dtmPublishedDateFrom As Date = #1/1/1900#, _
                           Optional ByVal dtmPublishedDateTo As Date = #12/31/3999#, _
                           Optional ByVal intCateId As Integer = -1)

        Dim intUserId As Integer = Session("UserID")

        Using data As New VSEntities
            Dim arrSearch() As String = {iPage.ToString, strTitle.ToString, intStoreId.ToString, dtmCreatedFrom, _
                                         dtmCreatedTo, intIsSellOff.ToString, intIsHot.ToString, intStatusId.ToString, _
                                         dtmPublishedDateFrom, dtmPublishedDateTo, intCateId.ToString, intUserId.ToString}

            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim p As List(Of uspProductFrontEndSelectAll_Result) = data.uspProductFrontEndSelectAll(strTitle, _
                                                                                   intStoreId, _
                                                                                   dtmCreatedFrom, _
                                                                                   dtmCreatedTo, _
                                                                                   intIsSellOff, _
                                                                                    intIsHot, _
                                                                                    intStatusId, _
                                                                                    dtmPublishedDateFrom, _
                                                                                    dtmPublishedDateTo, _
                                                                                    intCateId, _
                                                                                    intUserId, _
                                                                                    iPage, intPag_Size).ToList

            Dim strKey_Name() As String = {"ProductId", "Title", "QueryString"}

            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault.Total()

            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If

            Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String

        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip), arrSearch(1), arrSearch(2), arrSearch(3), _
                   arrSearch(4), arrSearch(5), arrSearch(6), _
                   arrSearch(7), arrSearch(8), arrSearch(9), arrSearch(10))

        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"

    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("ProductId").ToString
            Dim q = (From p In data.Products Where p.ProductId = intId Select p).FirstOrDefault
            Try
                Dim a = (From p In data.ProductImages Where p.ProductId = intId Select p).ToList
                For Each x In a
                    data.ProductImages.DeleteObject(x)
                Next

                data.Products.DeleteObject(q)

                data.SaveChanges()
                Insert_App_Log("Delete Product:" & txtTitle.Text.Trim & "", Function_Name.Product, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại hãy thử lại hoặc liên lạc với quản trị site.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        intTotal += 1
                        intId = grdShow.DataKeys(item.RowIndex)("ProductId").ToString
                        Dim q = (From p In data.Products Where p.ProductId = intId Select p).FirstOrDefault
                        Try
                            Dim a = (From p In data.ProductImages Where p.ProductId = intId Select p).ToList
                            For Each x In a
                                data.ProductImages.DeleteObject(x)
                            Next
                            data.Products.DeleteObject(q)
                            data.SaveChanges()
                            Insert_App_Log("Delete Product:" & txtTitle.Text.Trim & "", Function_Name.Product, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                            intCount += 1
                        Catch ex As Exception
                        End Try
                    End If
                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid(1, , Session("StoreId"))
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            hplEdit.NavigateUrl = MainDomain & "chinh-sua-san-pham.html?Id=" & grdShow.DataKeys(e.Row.RowIndex)("ProductId").ToString
            Dim hplTitle As HyperLink = CType(e.Row.FindControl("hplTitle"), HyperLink)
            hplTitle.NavigateUrl = MainDomain & grdShow.DataKeys(e.Row.RowIndex)("QueryString").ToString & "-" & grdShow.DataKeys(e.Row.RowIndex)("ProductId").ToString & ".html"
            hplTitle.Text = grdShow.DataKeys(e.Row.RowIndex)("Title").ToString
        End If
    End Sub
#End Region
#Region "Search"
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click

        BindToGrid(1, txtTitle.Text.Trim, -1, StringToDate(txtCreatedFrom.Text.Trim, "dd/mm/yyyy"), StringToDate(IIf(String.IsNullOrEmpty(txtCreatedTo.Text.Trim) = True, "31/12/3999", txtCreatedTo.Text.Trim), "dd/mm/yyyy"), _
                   chkIsselloff.SelectedValue, -1, ddlStatus.SelectedValue, _
                   StringToDate(txtPublisheddateFrom.Text.Trim, "dd/mm/yyyy"), _
                    StringToDate(IIf(String.IsNullOrEmpty(txtPublisheddateTo.Text.Trim) = True, "31/12/3999", txtPublisheddateTo.Text.Trim), "dd/mm/yyyy"), ddlType.SelectedValue)

    End Sub

    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
        txtTitle.Text = ""
        txtCreatedFrom.Text = ""
        txtCreatedTo.Text = ""
        txtCreatorid.Text = ""

        ddlType.SelectedValue = -1
        chkIsselloff.SelectedValue = -1
        chkIshot.SelectedValue = -1
        ddlStatus.SelectedValue = -1
        txtPublisheddateFrom.Text = ""
        txtPublisheddateTo.Text = ""
        drpPage_Size.SelectedIndex = -1S

        BindToGrid(1, Session("StoreId"))
    End Sub

    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1), arrSearch(2), arrSearch(3), _
                   arrSearch(4), arrSearch(5), arrSearch(6), _
                   arrSearch(7), arrSearch(8), arrSearch(9), arrSearch(10))
    End Sub
#End Region



End Class
